<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>出入库信息管理</title>
<meta name="decorator" content="default" />
<meta http-equiv="Expires" CONTENT="0">
<meta http-equiv="Cache-Control" CONTENT="no-cache">
<meta http-equiv="Pragma" CONTENT="no-cache">
<link href="${ctxStatic}/bootstrap-editable/css/bootstrap-editable.css" rel="stylesheet" />
<link href="${ctxStatic}/bootstrap-table/bootstrap-table.min.css" rel="stylesheet" />
<script src="${ctxStatic}/bootstrap-editable/js/bootstrap-editable.js"></script>
<script src="${ctxStatic}/bootstrap-table/bootstrap-table.js"></script>
<script src="${ctxStatic}/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
<script src="${ctxStatic}/bootstrap-table/extensions/editable/bootstrap-table-editable.js"></script>
<script src="${ctxStatic}/common/format/formatOrderData.js"></script>
<script src="${ctxStatic}/common/change/change.js"></script>
<script type="text/javascript">
	$(function() {
		//$("#name").focus();
		$("#inputForm").validate({
			submitHandler : function(form) {
				postOrderDetil(form);
			},
			ignore : "",
			errorContainer : "#messageBox",
			errorPlacement : function(error, element) {
				$("#messageBox").text("输入有误，请先更正。");
				if (element.is(":checkbox") || element.is(":radio")
						|| element.parent().is(".input-append")) {
					error.appendTo(element.parent().parent());
				} else {
					error.insertAfter(element);
				}
			}
		});
		$('#tab').bootstrapTable({
			url: "${ctx}/order_detail/bsVaccineOrderDetail/getOrderDetailById",
	    	toolbar: "#toolbar",
	    	clickToSelect :true,
	    	uniqueId: "id",
	    	queryParams: function (param) {
	            return {id :'${bsVaccineOrder.id}'};
	        } ,
	        columns: [{
	        	field:"选择",checkbox: true
	        }, {
	            field: 'id',
	            title: 'id',
	            visible: false
	        }, {
	            field: 'index',
	            title: 'index',
	            visible: false 
	        }, {
	            field: 'batchnoId',
	            title: 'batchnoId',
	            visible: false 
	        }, {
	            field: 'batchType',
	            title: '类型',
	            formatter:formatBatchType
	        }, {
	            field: 'name',
	            title: '疫苗名称/注射器类型'
	        }, {
	            field: 'sort',
	            title: '属性',
	            width : '150px',
	            editable: {
                    type: 'select2',
	                inputclass:'input-mini',
	                mode:'inline',
	                source: function (a,b,c,d) {
                        var list = JSON.parse('${fns:getDictListJson("bs_vaccine_type")}');
                        var result = [];
                        for (var i in list) {
                        	result.push({
                        		text : list[i].label,
                        		value : list[i].value
                        	});
                        }
                        return result;
                    }
	            }
	        }, {
	            field: 'companyName',
	            title: '生产企业'
	        }, {
	            field: 'companyCode',
	            title: '生产企业编码',
	            visible:false 
	        }, {
	            field: 'batchno',
	            title: '批号',
	            formatter:formatBatchno
	        }, {
	            field: 'spec',
	            title: '规格(剂/支或粒)',
	            formatter:formatSpec
	        }, {
	            field: 'dose',
	            title: '剂量'
	        }, {
	            field: 'vaccExpDate',
	            title: '有效日期',
	            formatter:formatDate
	        }, {
	            field: 'num',
	            title: '数量',
	            width:'150px',
	            editable: {
	                type: 'text',
	                title: '出库数量',
	                emptytext : '0',
	                inputclass:'input-mini',
	                mode:'inline',
	                validate: function (v) {
	                	var num = parseInt(v)
	    				var num_reg = /^\+?[1-9][0-9]*$/;
	    				if (!num_reg.test(v)) {
	    					return '出库数量不合法';
	    				}
	                }
	            }
	        }, {
	            field: 'orignprice',
	            title: '成本价格',
	            width:'150px',
	            editable: {
	                type: 'text',
	                title: '成本价格',
	                emptytext : '0.0',
	                inputclass:'input-mini',
	                mode:'inline',
	                validate: function (v) {
	    				var sellprice_reg = /^\d+(\.\d+)?$/;
	    				if (!sellprice_reg.test(v)) {
	    					return '价格不合法';
	    				}
	                }
	            }
	        }, {
	            field: 'sellprice',
	            title: '出售价格',
	            width:'150px',
	            editable: {
	                type: 'text',
	                title: '出售价格',
	                emptytext : '0.0',
	                inputclass:'input-mini',
	                mode:'inline',
	                validate: function (v) {
	    				var sellprice_reg = /^\d+(\.\d+)?$/;
	    				if (!sellprice_reg.test(v)) {
	    					return '价格不合法';
	    				}
	                }
	            }
	        }],
	        onEditableSave: function (field, row, oldValue, $el) {
	        	if(field == 'num'){
	        		var sum = $("#sumAmount").val();
		        	if(oldValue == ""){
		        		oldValue = 0;
		        	}
		        	sum = parseInt(sum)-parseInt(oldValue)+parseInt(row.num);
		        	$("#sumAmount").val(sum);
	        	}
	        	//入库时疫苗类型可以选择，价格对应发生变化
	        	if (field =='sort'){
					if (row.sort == "1"){
		        		row.orignprice = 0;
		        		row.sellprice = 0;
					}else{
		        		row.orignprice = '';
		        		row.sellprice = '';
					}
	        		$('#tab').bootstrapTable('updateByUniqueId', { id: row.batchnoId, 'row':row});
	        	}
				if (field !='sort'){
					setTimeout(function() {
						$('#tab').find('[data-uniqueid="' + row.batchnoId + '"]').next().find('[data-name="' + field + '"]').editable('show');
					},
					200);
				}
				if(field == 'orignprice'){
					if(row.sort == "2"){
						if(${office.grade == '50'}){
							row.sellprice = parseInt(row.orignprice) + 20;
						}else{
						    row.sellprice = parseInt(row.orignprice) + 10;
						}
					}
					$('#tab').bootstrapTable('updateByUniqueId', { id: row.batchnoId, 'row':row});
				}
            }
		});
		
		
		$("#BtnAddBatchno").click(function() {
			var val2 = $('input:radio[name="cType"]:checked').val();
			var companyCode = "";
			var checked = $("input:radio[name='company']:checked").val();
			if(checked == '2'){
				companyCode = $("#supplyorgCode2").val();
			}
			if (!val2) {
				val2 = '';
				layer.msg("请先选择疫苗类型！");
			}
			var url = "${ctx }/vaccinate/bsVaccineBatchno/getList?type="+val2+"&companyCode="+companyCode;
			var height = window.screen.availHeight * 0.6;
			var width = window.screen.availWidth * 0.7;
			layer.open({
				type : 2,
				title : '疫苗批次信息',
				shadeClose : true,
				skin : 'layui-layer-rim',
				shade : 0.8,
				resize : false,
				area : [ width + "px", height + "px" ],
				content : url
			});
		});
		
		$("#BtnDeleteBatchno").click(function() {
			var deleteData = $('#deleteData').val();
			var ids = $.map($('#tab').bootstrapTable('getSelections'), function (row) {
				/* return row.batchnoId; */
				if (row.id!=''){
					deleteData = deleteData+row.id+","
					return row.id;
				}else{
					return row.batchnoId;
				}
            });
			var num = $.map($('#tab').bootstrapTable('getSelections'), function (row) {
				return row.num;
            });
			$('#tab').bootstrapTable('remove', {
                field: 'id',
                values: ids
            });
			$('#tab').bootstrapTable('remove', {
                field: 'batchnoId',
                values: ids
            });
			var arr = Array.from(num);
			var sum = $("#sumAmount").val();
            for(var i=0;i<arr.length;i++){
            	if(arr[i] == ""){
            		arr[i] = "0";
            	}
            	sum = sum - parseInt(arr[i]);
            }
			$("#sumAmount").val(sum);
			$('#deleteData').val(deleteData);
		});
		
		$(".trantype").click(function() {
			var str = $(this).val();
			if (str == '3') {
				$(".traninput")[0].readOnly = false;
			} else {
				$(".traninput").val("");
				$(".traninput")[0].readOnly = true;
			}
		});
		$(".reftype").click(function() {
			var str = $(this).val();
			if (str == '3') {
				$(".refinput")[0].readOnly = false;
			} else {
				$(".refinput").val("");
				$(".refinput")[0].readOnly = true;
			}
		});

		
		$(".company").click(function(){
			var str = $(this).val();
			if (str == '1') {
				$("#company_treeselect").show();
				$("#company_select").hide();
				$("#company_input").hide();
			} else if (str == '2'){
				$("#company_treeselect").hide();
				$("#company_select").show();
				$("#company_input").hide();
			}else {
				$("#company_treeselect").hide();
				$("#company_select").hide();
				$("#company_input").show();
			}
		});
		initVaccCompanyName(bsVaccineOrder.supplyorgCode,bsVaccineOrder.supplyorgName);
	});

	var bsVaccineOrder = JSON.parse('${fns:toJson(bsVaccineOrder)}');
	
	function postOrderDetil(form) {//表单保存时  将此方法中的数据尽行保存
		//校验疫苗运输方式
		var val = $('input:radio[name="transportation"]:checked').val();
		if (!val) {
			$(".t-msg").find("font").text("必填信息");
			return;
		}
		var val1 = $('input:radio[name="refrigeratetype"]:checked').val();
		if (!val1) {
			$(".r-msg").find("font").text("必填信息");
			return;
		}
		//校验疫苗疫苗类型
		var val2 = $('input:radio[name="cType"]:checked').val();
		if (!val2) {
			$(".type-msg").find("font").text("必填信息");
			return;
		}

		//校验生产厂商编码
		var val3 = $('input:radio[name="company"]:checked').val();
		if (val3 =='1'){
			var supplyorgCode1 = $("#supplyorgCode1Id").val();
			var supplyorgName1 = $("#supplyorgCode1Name").val();
			if (!supplyorgCode1) {
				layer.msg("未选择供货单位！");
				return;
			}
			$("#supplyorgCode").val(supplyorgCode1);
			$("#supplyorgName").val(supplyorgName1);
		}else if (val3 =='2'){
			var supplyorgCode2 = $("#supplyorgCode2").val();
			if (!supplyorgCode2) {
				layer.msg("未选择供货单位！");
				return;
			}
			var supplyorgName2 = $("#supplyorgCode2").find("option:selected").text();
			$("#supplyorgCode").val(supplyorgCode2);
			$("#supplyorgName").val(supplyorgName2);
		}else{
			$("#supplyorgCode2").val("").select2();
			var supplyorgName3 = $("#supplyorgName3").val();
			$("#supplyorgName").val(supplyorgName3);
		}
		var rows = $('#tab').bootstrapTable('getData');
		var rowIndex = rows.length;
		var result = false;var checkPrice = true;var checkSort = true;
		if (rowIndex > 0) {
			for(var i = 0;i<rowIndex;i++ ){
				/* for(var j = i+1; j < rowIndex; j++){
					if(rows[i].batchnoId == rows[j].batchnoId && rows[i].orignprice == rows[j].orignprice){
						layer.alert("该批号 ( "+rows[i].batchno+" ) 存在多条相同的记录，请重新确认后在保存！！！", {
							  skin: 'layui-layer-molv' //样式类名
							  ,closeBtn: 0
							});
						return;
					}
				} */
				var num = parseInt(rows[i].num);
				var sellprice = parseFloat(rows[i].sellprice);
				var orignprice = parseFloat(rows[i].orignprice);
				var sort = rows[i].sort;
				var num_reg = /^\+?[1-9][0-9]*$/;
				if ( rows[i].sort != val2){
					layer.msg("疫苗种类不符合，请确认疫苗种类");
					return;
				}
				if (!num_reg.test(rows[i].num) || num < 0 ) {
					layer.msg("入库数量不合法！");
					return;
				}
				var sellprice_reg = /^\d+(\.\d+)?$/;
				if (!sellprice_reg.test(sellprice)) {
					return '价格不合法!';
				}
				if (sort == "1" && (sellprice != 0 || orignprice != 0 )) {
					checkPrice = false;
				}
				if (val3 =='2'){
					if(rows[i].companyCode != supplyorgCode2){
						layer.msg("疫苗生产企业与所选供货单位不一致！");
						return;
					}
				}
			}
			$("#tableData").val(JSON.stringify(rows));
			if(!checkPrice){
				layer.msg("存在一类疫苗价格不为零");
			}else{
				layer.confirm('确定保存？', {
					icon: 3, title:'提示',
					btn : [ '保存', '取消' ]
				}, function() {
					layer.load(2);
					loading('正在提交，请稍等...');
					form.submit();
				});
			}
		}else{
			layer.msg("入库单数据为空");
		}
	}
	
	function getInfo(obj) {
		$('#tab').bootstrapTable('getData', false);
		var rows = $('#tab').bootstrapTable('getData');
		for(var i = 0 in rows){
			if(obj.batchnoId == rows[i].batchnoId){
				layer.msg("该批号已在出入库单中，请勿多次选择");
				return;
			}
		}
		var url = "${ctx }/vaccinate/bsVaccineBatchno/getBatchnoInfo";
		$.ajax({
			url : url,
			type : "POST",
			dataType : "json",
			async : false,
			data : {
				"id" : obj.batchnoId
			},
			success : function(data) {
				var tr = {
					id : '',
					batchnoId : data.id,
					batchType : data.batchType,
					sort : data.type,
					name : data.vaccineName,
					companyName : data.companyName,
					companyCode : data.companyCode,
					batchno : data.batchno,
					secondBatchno : data.secondBatchno,
					spec : data.spec,
					dose : data.dose,
					vaccExpDate : data.outBoundDate,
					num : ''
				}
				if (data.type == 2){
					tr.orignprice = '';
					tr.sellprice = '';
				}else{
					tr.orignprice = 0;
					tr.sellprice = 0;
				}
				$('#tab').bootstrapTable('append', tr);
			},
			error : function() {
				return;
			}
		});
	}

	var specDic = jQuery.parseJSON('${fns:getDictListJson("syringe_spec")}');
	var batchTypeDic = JSON.parse('${fns:getDictListJson("batch_type")}');
</script>
<style type="text/css">
input[type="checkbox"] {
	display: block;
}
.maxWidth{
	width: 210px;
}
.input-xlarge-search {
	width: 266px;
}
.inputType{
    background-color: rgb(255, 255, 255);
    box-shadow: rgba(0, 0, 0, 0.075) 0px 1px 1px inset;
    border-width: 1px;
    border-style: solid;
    border-color: rgb(204, 204, 204);
    border-image: initial;
    transition: border 0.2s linear, box-shadow 0.2s linear;
    border-radius: 4px;
    height: 10px;
    font-size: 14px;
    line-height: 10px;
    padding: 4px 6px;
}
</style>
</head>
<body>
	<ul class="nav nav-tabs">
		<li class="active"><a href="#">疫苗入库</a>
		</li>
	</ul>
	<br />
	<form:form id="inputForm" modelAttribute="bsVaccineOrder" action="${ctx}/order/bsVaccineOrder/update" method="post" class="form-horizontal">
		<form:hidden path="id"/>
		<input id="receiveorgcode" type="hidden" name="receiveorgcode"
			value="${bsVaccineOrder.receiveorgcode}">
		<input id="tableData" type="hidden" name="tableData">
		<input id="deleteData" type="hidden" name="deleteData">
		<input id="supplyorgCode" type="hidden" name="supplyorgCode">
		<input id="supplyorgName" type="hidden" name="supplyorgName">
		<input id="orderType" type="hidden" name="orderType"
			value="${bsVaccineOrder.orderType}">
		<input id="orderStatus" type="hidden" name="orderStatus"
			value="${bsVaccineOrder.orderStatus}">
		<input id="tempStatus" type="hidden" name="tempStatus"
			value="${bsVaccineOrder.tempStatus}">
		<input id="createcode" type="hidden" name="createcode"
			value="${bsVaccineOrder.createcode}">
		<input id="createorgName" type="hidden" name="createorgName"
			value="${bsVaccineOrder.createorgName}">
		<sys:message content="${message}" />
		<div class="row-fluid">
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font
						color="red">*</font> </span>入库日期：</label>
				<div class="controls">
					<input name="outboundDate" type="text" maxlength="20"
						class="span6 Wdate required" readonly
						value="<fmt:formatDate value="${bsVaccineOrder.outboundDate}" pattern="yyyy-MM-dd"/>"
						onclick="WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:true});" />
				</div>
			</div>
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font
						color="red">*</font> </span>类型：</label>
				<div class="controls">
					<form:select path="orderType" readonly="true" disabled="true"
						class="span6 required ordertype">
						<form:options items="${fns:getDictList('bs_order_ordertype')}"
							itemLabel="label" itemValue="value" htmlEscape="false" />
					</form:select>
				</div>
			</div>
		</div>

		<div class="row-fluid">
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font
						color="red">*</font> </span> 供货单位：</label>
				<div class="controls">
                    <span id = "company_treeselect" <c:if test="${fn:length(bsVaccineOrder.supplyorgCode) < 6}"> style = "display:none;" </c:if>>
                        <sys:treeselect2 id="supplyorgCode1" name="supplyorgCode1" value="${bsVaccineOrder.supplyorgCode}" labelName="supplyorgName1" labelValue="${bsVaccineOrder.supplyorgName}"
					        notAllowSelectParent ="true" notAllowSelectRoot = "true" title="单位" url="/sys/office/treeData2?areaType=3" cssClass="input-xlarge-search" layer = "true"/>
					</span>
					<span id = "company_select" <c:if test="${fn:length(bsVaccineOrder.supplyorgCode) >= 6 || empty bsVaccineOrder.supplyorgCode}"> style = "display:none;" </c:if>>
						<select name="supplyorgCode2" id="supplyorgCode2" class="span6 vaccCompanyName">
							<option value="" label="--请选择--"/> 
						</select>
					</span>
					<span id = "company_input" <c:if test="${not empty bsVaccineOrder.supplyorgCode}"> style = "display:none;" </c:if>>
						<input id="supplyorgName3" name="supplyorgName3" maxlength="255" class="span6 inputType" value="${bsVaccineOrder.supplyorgName}"/>
					</span>
					<span><input id = "company1" type="radio" name="company" value="1" class = "company"  <c:if test="${fn:length(bsVaccineOrder.supplyorgCode) >= 6}"> checked</c:if>>上级疾控</span>
					<span><input id = "company2" type="radio" name="company" value="2" class = "company"  <c:if test="${fn:length(bsVaccineOrder.supplyorgCode) > 0 && fn:length(bsVaccineOrder.supplyorgCode) < 6}"> checked</c:if>>生产厂商</span>
					<span><input id = "company3" type="radio" name="company" value="3" class = "company"  <c:if test="${empty bsVaccineOrder.supplyorgCode}"> checked</c:if>>其它</span>				
				</div>
			</div>
			<div class="control-group span6">
				<label class="control-label">配送单位：</label>
				<div class="controls">
					<form:input path="consignorName" htmlEscape="false" maxlength="50"
						class="span6" />
				</div>
			</div>
		</div>
		<div class="row-fluid">
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font
						color="red">*</font> </span> 收货单位：</label>
				<div class="controls">
					<form:input path="receiveorgName" readonly="true"
						htmlEscape="false" maxlength="255" class="span6 receive" />
				</div>
			</div>
			<div class="control-group span6">
				<label class="control-label">收货单位经手人：</label>
				<div class="controls">
					<form:input path="consigneeName" htmlEscape="false" maxlength="50"
						class="span6 " />
				</div>
			</div>
		</div>
		<div class="row-fluid">
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font
						color="red">*</font></span> 疫苗运输工具：</label>
				<div class="controls">
					<form:radiobuttons path="transportation"
						items="${fns:getDictList('bs_order_transportation')}"
						itemLabel="label" itemValue="value" class="required trantype" />
					<form:input path="otherTransportation" readonly="true"
						htmlEscape="false" maxlength="50" class="input-mini  traninput" />
				</div>
			</div>
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font
						color="red">*</font></span> 疫苗冷藏方式：</label>
				<div class="controls">
					<form:radiobuttons path="refrigeratetype"
						items="${fns:getDictList('bs_order_refrigeratetype')}"
						itemLabel="label" itemValue="value" class="required reftype" />
					<form:input path="otherRefrigeratetype" readonly="true"
						htmlEscape="false" maxlength="50" class="input-mini refinput" />
				</div>
			</div>
		</div>
		<div class="row-fluid">
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font color="red">*</font></span> 疫苗类型：</label>
				<div class="controls">
					<form:radiobuttons path="cType" items="${fns:getDictList('bs_vaccine_type')}"
						itemLabel="label" itemValue="value" class="required" />
					<span class="help-inline type-msg error"><font color="red"></font></span>
				</div>
			</div>
		</div>
		<div class="row-fluid">
			<div class="control-group">
				<label class="control-label">备注信息：</label>
				<div class="controls">
					<form:textarea path="remarks" htmlEscape="false" rows="3"
						style="width: 78%;resize: vertical;" maxlength="100"
						class="input-xlarge" placeholder="最多输入100个字" />
				</div>
			</div>
		</div>
		
		<div id="toolbar">
			<!-- <button id="BtnAdd" class="btn btn-primary" type="button">新增</button> -->
			<button id="BtnAddBatchno" class="btn btn-primary" type="button">选择批号</button>
			<button id="BtnDeleteBatchno" class="btn btn-primary" type="button">删除</button>
		</div>
		<div class="control-group">
			<input id="tableData" type="hidden" name="tableData">
			<table id="tab" class="table table-bordered table-condensed">
			</table>
		</div>
		<div class="form-actions">
			<shiro:hasPermission name="order:bsVaccineOrder:edit">
			   <input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" />
			</shiro:hasPermission>
		    <input id="btnCancel" class="btn btn-primary" type="button" value="返 回" onclick="history.go(-1)" />
		    <div class="pull-right">
		       <span class="add-on" style="font-weight:bold;">合计入库数量:</span>
               <input class="input-mini" id="sumAmount" type="text" value="${payment.SUMVACCNUM}" style="font-size: 16px;" readonly="readonly"/>
		    </div>
		</div>
	</form:form>
</body>
</html>